<?php

namespace Database\Seeders;

use App\Models\Bar;
use App\Models\BarMember;
use App\Models\Favorite;
use App\Models\Post;
use App\Models\PostLike;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class PostSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // 获取所有贴吧和用户
        $bars = Bar::with('members')->get();
        $users = User::all();

        if ($bars->isEmpty() || $users->isEmpty()) {
            $this->command->warn('没有贴吧或用户数据，请先运行 BarSeeder 和 UserSeeder');
            return;
        }

        $this->command->info('开始创建帖子数据...');

        DB::transaction(function () use ($bars, $users) {
            foreach ($bars as $bar) {
                // 获取贴吧成员（包括吧主）
                $barMembers = $bar->members->pluck('user_id')->toArray();
                if (empty($barMembers)) {
                    continue;
                }

                // 每个贴吧创建 3-8 个帖子
                $postCount = fake()->numberBetween(3, 8);
                $postCreatedAt = $bar->created_at;

                for ($i = 0; $i < $postCount; $i++) {
                    // 随机选择一个贴吧成员作为作者
                    $authorId = fake()->randomElement($barMembers);
                    $author = $users->firstWhere('id', $authorId);

                    if (!$author) {
                        continue;
                    }

                    // 创建帖子
                    $post = Post::create([
                        'title' => $this->generatePostTitle(),
                        'content' => $this->generatePostContent(),
                        'user_id' => $authorId,
                        'bar_id' => $bar->id,
                        'images' => null,
                        'views' => fake()->numberBetween(10, 5000),
                        'like_count' => 0,
                        'reply_count' => 0,
                        'is_pinned' => false,
                        'is_essence' => false,
                        'pinned_at' => null,
                        'created_at' => fake()->dateTimeBetween($postCreatedAt, 'now'),
                        'updated_at' => now(),
                    ]);

                    // 更新贴吧帖子数（在事务外统一更新）
                }

                // 每个贴吧设置 1-2 个置顶帖子（由吧主发布）
                $ownerId = $bar->owner_id;
                $ownerPosts = Post::where('bar_id', $bar->id)
                    ->where('user_id', $ownerId)
                    ->limit(2)
                    ->get();

                foreach ($ownerPosts as $post) {
                    if (fake()->boolean(60)) { // 60% 概率置顶
                        $post->update([
                            'is_pinned' => true,
                            'pinned_at' => $post->created_at,
                        ]);
                    }
                }

                // 每个贴吧设置 2-5 个精华帖子
                $essencePosts = Post::where('bar_id', $bar->id)
                    ->inRandomOrder()
                    ->limit(fake()->numberBetween(2, 5))
                    ->get();

                foreach ($essencePosts as $post) {
                    $post->update(['is_essence' => true]);
                }
            }

            // 创建点赞和收藏数据
            $this->createLikesAndFavorites($users);

            // 更新统计信息
            $this->updateStatistics();
        });

        // 更新所有贴吧的帖子数
        foreach ($bars as $bar) {
            $bar->update([
                'post_count' => Post::where('bar_id', $bar->id)->count(),
            ]);
        }

        $totalPosts = Post::count();
        $totalLikes = PostLike::count();
        $totalFavorites = Favorite::count();

        $this->command->info("帖子数据填充完成！");
        $this->command->info("共创建 {$totalPosts} 个帖子");
        $this->command->info("共创建 {$totalLikes} 条点赞记录");
        $this->command->info("共创建 {$totalFavorites} 条收藏记录");
    }

    /**
     * 生成帖子标题
     */
    private function generatePostTitle(): string
    {
        $titles = [
            'React 19 新特性深度解析',
            'Vue 3 组合式 API 最佳实践',
            'Laravel 10 新功能体验分享',
            'Python 数据分析实战教程',
            'JavaScript 异步编程进阶',
            'Git 工作流最佳实践',
            'Docker 容器化部署指南',
            '前端性能优化技巧分享',
            'UI 设计趋势 2024',
            '平面设计配色技巧',
            '美食制作教程分享',
            '旅行攻略分享',
            '健身计划制定方法',
            '读书笔记分享',
            '电影推荐',
            '求助：关于某个问题',
            '讨论：大家怎么看？',
            '请教：最佳实践是什么？',
            '经验分享：从入门到精通',
            '技术总结：近期学习心得',
        ];

        return fake()->randomElement($titles);
    }

    /**
     * 生成帖子内容
     */
    private function generatePostContent(): string
    {
        $prefixes = [
            '最近在学习',
            '今天想和大家分享',
            '经过一段时间的实践',
            '刚接触这个领域',
            '最近遇到了一个问题',
        ];

        $content = fake()->randomElement($prefixes) . '，' . fake()->sentence(15, 30);
        $content .= "\n\n" . fake()->paragraph(2, 4);
        $content .= "\n\n" . fake()->paragraph(2, 4);

        return $content;
    }

    /**
     * 创建点赞和收藏数据
     */
    private function createLikesAndFavorites($users): void
    {
        $posts = Post::all();

        foreach ($posts as $post) {
            // 10-50% 的用户会点赞（根据帖子热度）
            $likeProbability = fake()->numberBetween(10, 50);
            $likeCount = (int)($users->count() * $likeProbability / 100);
            $likeCount = min($likeCount, $users->count());

            if ($likeCount > 0) {
                $likers = $users->random($likeCount);
                foreach ($likers as $user) {
                    // 确保作者不会给自己点赞
                    if ($user->id !== $post->user_id) {
                        PostLike::create([
                            'post_id' => $post->id,
                            'user_id' => $user->id,
                            'created_at' => fake()->dateTimeBetween($post->created_at, 'now'),
                            'updated_at' => now(),
                        ]);
                    }
                }
            }

            // 3-15% 的用户会收藏
            $favoriteProbability = fake()->numberBetween(3, 15);
            $favoriteCount = (int)($users->count() * $favoriteProbability / 100);
            $favoriteCount = min($favoriteCount, $users->count());

            if ($favoriteCount > 0) {
                $favoriters = $users->random($favoriteCount);
                foreach ($favoriters as $user) {
                    Favorite::create([
                        'post_id' => $post->id,
                        'user_id' => $user->id,
                        'created_at' => fake()->dateTimeBetween($post->created_at, 'now'),
                        'updated_at' => now(),
                    ]);
                }
            }
        }
    }

    /**
     * 更新统计信息
     */
    private function updateStatistics(): void
    {
        $posts = Post::all();

        foreach ($posts as $post) {
            $likeCount = PostLike::where('post_id', $post->id)->count();
            $post->update(['like_count' => $likeCount]);
        }
    }
}
